//
//  PublishCommentViewController.swift
//  Owner
//
//  Created by Selina on 28/8/2020.
//  Copyright © 2020 Selina. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

class PublishCommentViewController: BaseViewController {
    
    private var contentId: Int64!
    private var commentLevel: Int!
    private var parentCommentId: Int64!
    private let safeDistance: CGFloat = IPHONE_X ? 33.0 : 0.0
    private var keyboardChangeDic:[String:Any]?
    private var keyboardHeight:CGFloat?
    private var viewModel: PublishCommentViewModel!
    lazy var publishInputView: PublishCommentInputView = {
        let view = PublishCommentInputView()
        self.view.addSubview(view)
        //        view.isUserInteractionEnabled = false
        view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.safeView.snp.top)
        }
        return view
    }()
    
    lazy var safeView: UIView = {
        let view = UIView()
        self.view.addSubview(view)
        view.backgroundColor = .white
        view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(self.safeDistance)
        }
        return view
    }()
    
    // MARK: - =====================init====================
    convenience init(contentId: Int64,commentLevel:Int,parentCommentId:Int64, callBack: CallBack?) {
        self.init()
        self.contentId = contentId
        self.commentLevel = commentLevel
        self.parentCommentId = parentCommentId
        self.callBack = callBack
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = "#000".color(alpha: 0.3)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissCallBack))
        tapGesture.delegate = self
        self.view.addGestureRecognizer(tapGesture)
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoadWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        //点击发送事件
        publishInputView.publishButton.addTarget(self, action: #selector(publishCommentRequest), for: .touchUpInside)
        
        //获取焦点
        self.publishInputView.textView.becomeFirstResponder()
        self.publishInputView.textView.inputAccessoryView = nil
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        //局部禁用自动toolbar,防止弹跳
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.view.endEditing(true)
    }
    
    override func addViewModel() {
        viewModel = PublishCommentViewModel(text: publishInputView.textView.rx.text.orEmpty.asObservable())
        //
        viewModel.textNumValid.bind(to: publishInputView.publishButton.rx.isEnabled).disposed(by: disposeBag)
        //
        viewModel.textNum.bind(to: publishInputView.textNumLabel.rx.text).disposed(by: disposeBag)
    }
    // MARK: - =====================请求====================
    @objc func publishCommentRequest() {
        
        Service.TrendProvider().request(.publishComment(contentId: contentId,commentLevel:commentLevel,parentCommentId:parentCommentId, commentText: publishInputView.textView.text)) { (result) in
            
            switch result {
            
            case let .success(response):
                if let dic = try? response.mapJSON() as? NSDictionary {
                    if let code = dic.value(forKey: "code") as? String {
                        if code == "0" {
                            if self.callBack != nil {
                                self.callBack!(nil)
                            }
                            self.dismissCallBack()
                        }
                    }
                }
                break
            case .failure(_): break
            }
        }
    }
    // MARK: - =====================事件====================
    @objc func dismissCallBack() {
       
        UIView.animate(withDuration: 2) {
            self.publishInputView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.safeView.snp.top)
            }
            
        } completion: { (result) in
            Log.info(result)
            self.view.backgroundColor = .clear
            if(result){
                self.dismiss(animated: true, completion: nil)
            }
        }

    }
    
    @objc func keyBoardWillShow(_ notification: Notification) {
        let user_info = notification.userInfo
        let beginRect = (user_info?[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let endRect = (user_info?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        Log.info("开始:\(beginRect)")
        Log.info("结束:\(endRect)")
        
        //        if (beginRect.origin.y >= SCREEN_HEIGHT) && (endRect.size.height > 0) || (beginRect.origin.y  > endRect.origin.y){
        
        let y = endRect.origin.y
        UIView.animate(withDuration: 2) {
            self.publishInputView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.safeView.snp.top).offset(-(SCREEN_HEIGHT - y - self.safeDistance))
            }
        }
        //        };
        
    }
    
    @objc func keyBoadWillHide(_ notification: Notification) {
        UIView.animate(withDuration: 2) {
            self.publishInputView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.safeView.snp.top)
            }
        }
    }
}

extension PublishCommentViewController: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        if touch.view != self.view {
            return false
        }
        return true
    }
}
